﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HitchHikersGuideToTheGalaxy.Models;

namespace HitchHikersGuideToTheGalaxy.Models
{
    public class VechicleDriverRepository : IVechicleDriverRepository
    {
        GalaxyDataContext db = new GalaxyDataContext();

        #region Default Add, Delete and save actions

        /// <summary>
        /// Add one VehicleDriver record to Database.
        /// </summary>
        /// <param name="vehicleDriver"></param>
        public void Add(VehicleDriver vehicleDriver)
        {
            db.VehicleDrivers.InsertOnSubmit(vehicleDriver);
        }

        /// <summary>
        /// Delete one VehicleDriver record from Database.
        /// </summary>
        /// <param name="vehicleDriver"></param>
        public void Delete(VehicleDriver vehicleDriver)
        {
            db.VehicleDrivers.DeleteOnSubmit(vehicleDriver);
        }

        /// <summary>
        /// Save changes made to Database.
        /// </summary>
        public void Save()
        {
            db.SubmitChanges();
        }

        #endregion

        #region Querys

        /// <summary>
        /// Fetch all VehicleDriver's records from Database.
        /// </summary>
        /// <returns></returns>
        public IQueryable<VehicleDriver> FindAllVehicleDrivers()
        {
            return db.VehicleDrivers;
        }

        /// <summary>
        /// Find a VehicleDriver record in Database.
        /// </summary>
        /// <param name="ssn"></param>
        /// <returns></returns>
        public VehicleDriver FindVehicleDriver(string ssn)
        {
            return db.VehicleDrivers.SingleOrDefault(d => d.UserInfoSSN == ssn);
        }

        /// <summary>
        /// Get the Id.
        /// </summary>
        /// <param name="ssn"></param>
        /// <returns></returns>
        public int GetId(string ssn)
        {
            return (from vd in db.VehicleDrivers
                    where vd.UserInfoSSN == ssn
                    select vd.Id).SingleOrDefault<int>();
        }

        public VehicleDriver GetVehicleDriverByNumberPlate(string numberPlate)
        {
            return (from vd in db.VehicleDrivers
                    from v in db.Vehicles
                    where vd.VehicleId == v.Id && v.NumberPlate == numberPlate
                    select vd).Single();
        }

        #endregion
    }
}
